<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>

</head>

<body>
    <h1>拦截器练习</h1>
    <input type="text" id="ipt">
    <button id="btn">提交</button>
    <script>
        const myAxios = axios.create({
            baseURL: '/', //配置公共路径
            timeout: 10000, //配置超时时间
            headers: {} //配置请求头
        })

        // 添加请求拦截器
        myAxios.interceptors.request.use(function (config) {
            // 在发送请求之前做些什么
            //1.获取token,并让请求头携带token
            const token = 'jffnjsddsdd.wehfvnn255hddf.uuuurrrr'
            config.headers.token = token;

            //2.让进度条开始
            NProgress.start();

            return config;
        }, function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        });

        // 添加响应拦截器
        myAxios.interceptors.response.use(function (response) {
            // 对响应数据做点什么

            //1.让进度条结束
            NProgress.done();
            
            //2.对请求到的结果进行处理,只拿正确的信息,如果错误的信息,中间交给异常处理
            if(response.data.code !== 10000){
                return Promise.reject(response.data.msg)
            }

            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
        const oBtn = document.getElementById('btn')
        const oIpt = document.getElementById('ipt')
        oBtn.onclick = async function () {
            const iptValue = oIpt.value
            try {
                const result = await myAxios.get('/user', {
                    params: {
                        userId: iptValue
                    }
                })
                console.log(result, 'result');
            } catch (e) {
                console.log('出现错误', e);
            }
        }
    </script>
</body>

</html>